#include "trypsyn_dsp.h"
#include "id3_proc.h"
#include "id3_defs.h"

int main(int argc, char **argv) {

	trypsyn_id3_header header;
	trypsyn_id3_frame_header_v2 frame_header_v2;
	trypsyn_id3_frame_header_v4 frame_header_v4;
	
	FILE *fp = NULL;
	int file_type = 0;
	char *file_name = argv[1];
	
	trypsyn_open(file_name, &file_type, &fp);
	trypsyn_id3_read_header(&header, fp);
	trypsyn_id3_print_header(&header);

	int frame_size = 0;
	
	trypsyn_uint8_t encoding;
	trypsyn_uint8_t *data;
	trypsyn_uint8_t byte_test;
	trypsyn_uint32_t sync_word;
	int i, j = 1;
	int exit_loop = 1;
	
	fread(&byte_test, 1, 1, fp);
	fseek(fp, -1, SEEK_CUR);

	while(1) {
		
		exit_loop = 1;
		
		if((byte_test & 0x0F) == 0x0F) {
		
			printf("%d\n", byte_test);
		
			fread(&sync_word, 4, 1, fp);
			fseek(fp, -4, SEEK_CUR);
			if((sync_word & 0xFFF0) || (sync_word & 0x0FFF)) {
				puts("found syncword");
				break;
			}
		}

		if(header.major_version == 2) {
	
			trypsyn_id3_read_frame_header_v2(&frame_header_v2, fp);
		
			if(frame_header_v2.identifier[0] != 'T') continue;
		
			trypsyn_id3_print_frame_header_v2(&frame_header_v2, j);
			frame_size = frame_header_v2.frame_size;

		} else if(header.major_version == 4) {

			trypsyn_id3_read_frame_header_v4(&frame_header_v4, fp);
			
			for(i = 0; i < 5; i++) {
				if(strcmp(frame_header_v4.identifier, trypsyn_id3_v4_std_frames[i]) == 0) {
					if(frame_header_v4.identifier[0] == 'T') {
						exit_loop = 0;
						break;
					}
				}
			}

			if(exit_loop) continue;

			trypsyn_id3_print_frame_header_v4(&frame_header_v4, j);
			frame_size = frame_header_v4.frame_size;

		}
	
		j++;
		fread(&encoding, 1, 1, fp);
		printf("Frame text encoding: %d\n", encoding);

		data = (trypsyn_uint8_t *)malloc(sizeof(trypsyn_uint8_t) * frame_size);
		fread(data, 1, frame_size-1, fp);
		data[frame_size - 1] = '\0';

		printf("Frame data: %s\n", data);
		free(data);
		data = NULL;
	}
		
	fclose(fp);
	return 0;
}

